<template>
  <div class="h-full">
    <SearchCom
      :searchList="searchConfig"
      @search="handleSearch"
      @reset="handleReset"
    />
    <div class="table-container">
      <!-- 操作按钮 -->
      <div class="operation-bar">
        <el-button type="primary" @click="handleAdd">发布消息</el-button>
      </div>
      
      <el-table :data="tableData" style="width: 100%" border class="news-table">
        <el-table-column prop="title" label="消息标题" min-width="180" />
        
        <el-table-column prop="description" label="消息描述" min-width="300">
          <template #default="scope">
            <div class="description-text">{{ scope.row.description }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="图片" width="120">
          <template #default="scope">
            <el-popover placement="right" width="280" trigger="hover" v-if="scope.row.image">
              <template #default>
                <div class="news-big-img">
                  <img :src="scope.row.image" alt="消息图片" />
                </div>
              </template>
              <template #reference>
                <div class="news-img">
                  <img :src="scope.row.image" alt="消息图片" />
                </div>
              </template>
            </el-popover>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="readCount" label="已阅读用户数" width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.readCount }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="发布时间" width="180" />
        
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              title="确定要删除该消息吗？"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 引入编辑/新增消息组件 -->
    <NewsEdit 
      v-model:visible="editDialogVisible"
      :edit-data="currentEditData"
      @submit="handleSubmit"
      @cancel="handleEditCancel"
    />
  </div>
</template>

<script setup>
import { ref } from "vue";
import SearchCom from "@/components/SearchCom.vue";
import NewsEdit from "./edit.vue"; // 引入编辑组件
import { ElMessage, ElMessageBox } from 'element-plus';

const searchConfig = ref([
  {
    label: "消息标题",
    key: "title",
    type: "input",
  }
]);

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 编辑对话框显示状态
const editDialogVisible = ref(false);
// 当前编辑的数据
const currentEditData = ref(null);

// 模拟表格数据
const tableData = ref(
  Array.from({ length: 10 }, (_, index) => ({
    id: index + 1,
    title: `消息标题${index + 1}`,
    description: `这是消息的详细描述内容，可能会比较长，这里是示例文本这是消息的详细描述内容，可能会比较长，这里是示例文本${index + 1}`,
    image: index % 2 === 0 ? 'https://img-lang.55sld.com/channel1langimages/seller/goods/ZScpQ4FYJscQXRSuxtl.png' : '', // 一半有图片
    readCount: Math.floor(Math.random() * 1000),
    createTime: `2023-${(index % 12 + 1).toString().padStart(2, '0')}-${(index % 28 + 1).toString().padStart(2, '0')} ${Math.floor(Math.random() * 24).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}`
  }))
);

// 处理搜索
const handleSearch = (formData) => {
  console.log("搜索条件:", formData);
  // 实际项目中这里应该调用API进行搜索
  ElMessage.success('搜索请求已发送');
};

// 处理重置
const handleReset = () => {
  console.log("表单已重置");
  // 重置后可能需要重新加载初始数据
  ElMessage.info('表单已重置');
};

// 新增消息
const handleAdd = () => {
  currentEditData.value = null; // 置空编辑数据，表示新增
  editDialogVisible.value = true; // 显示对话框
};

// 编辑消息
const handleEdit = (row) => {
  currentEditData.value = { ...row }; // 设置当前编辑的数据
  editDialogVisible.value = true; // 显示对话框
};

// 处理编辑取消
const handleEditCancel = () => {
  currentEditData.value = null;
};

// 处理表单提交
const handleSubmit = (formData) => {
  if (currentEditData.value) {
    // 编辑模式
    const index = tableData.value.findIndex(item => item.id === formData.id);
    if (index !== -1) {
      tableData.value[index] = { ...formData };
      ElMessage.success(`消息: ${formData.title} 已更新`);
    }
  } else {
    // 新增模式
    const newId = Math.max(...tableData.value.map(item => item.id), 0) + 1;
    const now = new Date();
    const formattedDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
    
    tableData.value.unshift({
      ...formData,
      id: newId,
      readCount: 0,
      createTime: formattedDate
    });
    ElMessage.success(`消息: ${formData.title} 已发布`);
  }
  
  currentEditData.value = null;
};

// 删除消息
const handleDelete = (row) => {
  console.log("删除消息:", row);
  // 实际项目中这里应该调用API进行删除
  const index = tableData.value.findIndex(item => item.id === row.id);
  if (index !== -1) {
    tableData.value.splice(index, 1);
    ElMessage.success(`消息: ${row.title} 已删除`);
  }
};

// 处理页码变化
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  // 这里请求对应页的数据
};

// 处理每页数量变化
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  // 这里请求对应数量的数据
};
</script>

<style scoped lang="scss">
.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
}

.operation-bar {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.news-img {
  width: 80px;
  height: 80px;
  overflow: hidden;
  border: 1px solid #e2e5f6;
  border-radius: 4px;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.news-big-img {
  width: 250px;
  height: 250px;
  overflow: hidden;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}

.description-text {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
